#include "Socket.hpp"
#include <functional>
#include <memory>
#include <sys/wait.h>

using namespace SocketModule;

using ioserver_t = std::function<void(std::shared_ptr<Socket> &sock, InetAddr &client)>;

class TcpServer
{

public:
    TcpServer(uint16_t port, ioserver_t service)
        : _port(port),
          _listensockptr(std::make_unique<TcpSocket>()),
          _isrunning(false),
          _service(service)
    {
        _listensockptr->BuildTcpSocketMethod(_port);
    }


    void Start()
    {
        _isrunning=true;
        while(_isrunning)
        {
            InetAddr client;
            auto sock=_listensockptr->Accept(&client);
            if(sock==nullptr)
            {
                continue;
            }

            pid_t pid=fork();
            if(pid==0)
            {
                _listensockptr->Close();
                if(fork()>0)
                {
                    exit(OK);
                }
                _service(sock,client);
                sock->Close();
                exit(OK);
            }
            else if(pid<0)
            {
                LOG(LogLevel::FATAL)<<"fork error";
                exit(ExitCode::FORK_ERR);
            }
            else{
                sock->Close();
                int n=::waitpid(pid,nullptr,0);
                (void)n;

            }

        }

    }
    
private:
    uint16_t _port;
    std::unique_ptr<Socket> _listensockptr;
    bool _isrunning;
    ioserver_t _service;
};